package com.webwork.framework.security;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.webwork.project.system.dataobject.SysUser;
import com.webwork.project.system.service.IFuncUserSve;

public class CustomRealm extends AuthorizingRealm {
	
//	private static final Logger log = LoggerFactory.getLogger(CustomRealm.class);
	
	@Autowired
	private IFuncUserSve userSve;
	
	private Set<String> getPermissionsByUserName(String userName) {
		Set<String> set = new HashSet<String>();
		set.add("admin:select");
		return set;
	}
	
	private Set<String> getRolesByUserName(String userName) {
		Set<String> set = new HashSet<String>();
		set.add("admin");
		return set;
	}

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String userName = (String) principals.getPrimaryPrincipal();
		
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		// 角色加入AuthorizationInfo认证对象
		authorizationInfo.setRoles(this.getRolesByUserName(userName));
		// 权限加入AuthorizationInfo认证对象
		authorizationInfo.setStringPermissions(this.getPermissionsByUserName(userName));
		
		return authorizationInfo;
	}

	/**
	 * 登录认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
		if (token == null || token.getPrincipal() == null) {
			return null;
		}
		UsernamePasswordToken userToken = (UsernamePasswordToken) token;
		String userName = userToken.getUsername();
		
		SysUser user = userSve.getUsable(userName);
		if (user != null) {
			if (!StringUtils.isEmpty(user.getPassword())) {
				ByteSource credentialsSalt = ByteSource.Util.bytes(userName);	//暂时直接用账号名作为盐值
				SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userName, user.getPassword(), getName());
				//验证加盐
				authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(credentialsSalt));
				return authenticationInfo;
			} else {
				return null;
			}
		}
		return null;
	}
	
}
